// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import { routers, otherRouter, appRouter } from '../router/index'
import iView from 'iview'
import App from './App'

import router from './router'
import Cookies from 'js-cookie'
import Vuex from 'vuex'
import VueRouter from 'vue-router'
import Util from './libs/util'

import VueI18n from 'vue-i18n'
import Locales from './locale'
import zhLocale from 'iview/src/locale/lang/zh-CN'
import enLocale from 'iview/src/locale/lang/en-US'

Vue.config.productionTip = false
Vue.use(iView)
Vue.use(Vuex)
Vue.use(VueRouter)
Vue.use(VueI18n)
/* eslint-disable no-new */
// 自动设置语言
const navLang = navigator.language
const localLang = (navLang === 'zh-CN' || navLang === 'en-US') ? navLang : false
const lang = window.localStorage.getItem('language') || localLang || 'zh-CN'

Vue.config.lang = lang

// 多语言配置
const locales = Locales
const mergeZH = Object.assign(zhLocale, locales['zh-CN'])
const mergeEN = Object.assign(enLocale, locales['en-US'])
Vue.locale('zh-CN', mergeZH)
Vue.locale('en-US', mergeEN)

// 路由配置
const RouterConfig = {
  // mode: 'history',
  routes: routers
}
const router = new VueRouter(RouterConfig)

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  Util.title(to.meta.title)
  if (Cookies.get('locking') === '1' && to.name !== 'locking') {  // 判断当前是否是锁定状态
    iView.LoadingBar.finish()
    next(false)
    router.replace({
      name: 'locking'
    })
  } else if (Cookies.get('locking') === '0' && to.name === 'locking') {
    iView.LoadingBar.finish()
    next(false)
  } else {
    if (!Cookies.get('user') && to.name !== 'login') {  // 判断是否已经登录且前往的页面不是登录页
      next({
        name: 'login'
      })
    } else if (Cookies.get('user') && to.name === 'login') {  // 判断是否已经登录且前往的是登录页
      next({
        name: 'home'
      })
    } else {
      next()
    }
  }
})

router.afterEach(() => {
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})
// 状态管理
const store = new Vuex.Store({
  state: {
    routers: [
      otherRouter,
      ...appRouter
    ],
    menuList: [],
    tagsList: [...otherRouter.children],
    pageOpenedList: [],
    currentPageName: '',
    currentPath: [
      {
        title: '首页',
        path: '',
        name: 'home_index'
      }
    ],  // 面包屑数组
    openedSubmenuArr: [],  // 要展开的菜单数组
    menuTheme: '', // 主题
    theme: ''
  },
  getters: {

  },
  mutations: {
    setTagsList (state, list) {
      state.tagsList.push(...list)
    },
    increateTag (state, tagObj) {
      state.pageOpenedList.splice(1, 0, tagObj)
    },
    removeTag (state, name) {
      state.pageOpenedList.map((item, index) => {
        if (item.name === name) {
          state.pageOpenedList.splice(index, 1)
        }
      })
    },
    moveToSecond (state, index) {
      let openedPage = state.pageOpenedList[index]
      state.pageOpenedList.splice(index, 1)
      state.pageOpenedList.splice(1, 0, openedPage)
      localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)
    },
    setOpenedList (state) {
      state.pageOpenedList = localStorage.pageOpenedList ? JSON.parse(localStorage.pageOpenedList) : [otherRouter.children[0]]
    },
    setCurrentPath (state, pathArr) {
      state.currentPath = pathArr
    },
    setCurrentPageName (state, name) {
      state.currentPageName = name
    },
    addOpenSubmenu (state, name) {
      let hasThisName = false
      let isEmpty = false
      if (name.length === 0) {
        isEmpty = true
      }
      if (state.openedSubmenuArr.indexOf(name) > -1) {
        hasThisName = true
      }
      if (!hasThisName && !isEmpty) {
        state.openedSubmenuArr.push(name)
      }
    },
    clearOpenedSubmenu (state) {
      state.openedSubmenuArr.length = 0
    },
    changeMenuTheme (state, theme) {
      state.menuTheme = theme
    },
    changeMainTheme (state, mainTheme) {
      state.theme = mainTheme
    },
    lock (state) {
      Cookies.set('locking', '1')
    },
    unlock (state) {
      Cookies.set('locking', '0')
    },
    setMenuList (state, menulist) {
      state.menuList = menulist
    },
    updateMenulist (state) {
      let accessCode = parseInt(Cookies.get('access'))
      let menuList = []
      appRouter.forEach((item, index) => {
        if (item.access !== undefined) {
          if (Util.showThisRoute(item.access, accessCode)) {
            if (item.children.length <= 1) {
              menuList.push(item)
            } else {
              let i = menuList.push(item)
              let childrenArr = []
              childrenArr = item.children.filter(child => {
                if (child.access !== undefined) {
                  if (child.access === accessCode) {
                    return child
                  }
                } else {
                  return child
                }
              })
              menuList[i - 1].children = childrenArr
            }
          }
        } else {
          if (item.children.length <= 1) {
            menuList.push(item)
          } else {
            let i = menuList.push(item)
            let childrenArr = []
            childrenArr = item.children.filter(child => {
              if (child.access !== undefined) {
                if (Util.showThisRoute(child.access, accessCode)) {
                  return child
                }
              } else {
                return child
              }
            })
            menuList[i - 1].children = childrenArr
          }
        }
      })
      state.menuList = menuList
    },
    setAvator (state, path) {
      localStorage.avatorImgPath = path
    }
  },
  actions: {

  }
})

new Vue({
  el: '#app',
  router,
  store: store,
  template: '<App/>',
  components: { App }
})
